package com.example.addressbook;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    EditText userName,photo;
    Button insert,update,delete,query,queryAll;
    //查询返回的列
    String[] SQL_COLUMN =new String[]{
            ContactsContract.CommonDataKinds.Identity.RAW_CONTACT_ID,//row_contact_id
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,//display_name
            ContactsContract.CommonDataKinds.Phone.NUMBER//data1
    };
    //查询限制条件
    String mSelectClaus;

    //查询限制条件的内容
    String[] mSelectionArgs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        textView =findViewById(R.id.textView);//显示查询出的数据
        insert =findViewById(R.id.insertBtn);//添加按钮
        update =findViewById(R.id.updateBtn);//修改按钮
        delete =findViewById(R.id.deleteBtn);//删除
        query =findViewById(R.id.querytBtn);//查询
        queryAll =findViewById(R.id.queryAllBtn);//查询全部
        userName =findViewById(R.id.userName);//用户输入
        photo =findViewById(R.id.photo);//密码输入

        insert.setOnClickListener(new mClick());
        update.setOnClickListener(new mClick());
        delete.setOnClickListener(new mClick());
        query.setOnClickListener(new mClick());
        queryAll.setOnClickListener(new mClick());
        textView.setOnClickListener(new mClick());

        if(Build.VERSION.SDK_INT >=23){
            String[] permissions ={Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_CONTACTS};
            int i=0;
            for(String permission:permissions){
                //如果没有给权限就从新请求
                if(this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
                    this.requestPermissions(permissions,i++);
                }
            }
        }

    }

    private  class mClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.insertBtn:
                    insert();
                    break;
                case R.id.updateBtn:
                    update();
                    break;
                case R.id.deleteBtn:
                    delete();
                    break;
                case R.id.querytBtn:
                    query();
                    break;
                case R.id.queryAllBtn:
                    printQueryResult();
                    break;
                case R.id.textView:
                    Intent intent = new Intent(MainActivity.this,people.class);

                    startActivity(intent);}

            }
        }

        //新增
        void insert(){
            String name =userName.getText().toString();
            String phone =photo.getText().toString();
            ContentValues values =new ContentValues();
            //ContactsContract.RawContacts.CONTENT_URI 查询的URI
            Uri uri =getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI,values);
            long rawContentId =ContentUris.parseId(uri);//获取到插入的id
            if(!name.equals("")){
                values.clear();
                //插入姓名
                values.put(ContactsContract.Data.RAW_CONTACT_ID,rawContentId);//插入的id
                values.put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);//插入name的类型
                values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,name);//放入实际值

                getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);

            }

            //插入电话
            if(!phone.equals("")){
                values.put(ContactsContract.Data.RAW_CONTACT_ID,rawContentId);//插入的id
                values.put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                values.put(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,phone);
                getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);
            }

            Toast.makeText(getApplicationContext(),"添加成功",Toast.LENGTH_LONG).show();

            //查询后自动刷新TextView查看是否添加成功
            printQueryResult();
        }

        //修改
        void update(){
            String name =userName.getText().toString();
            String phone =photo.getText().toString();
            Long rawContactId=0L;
            Uri uri =Uri.parse("content://com.android.contacts/data");
            ContentResolver resolver = getContentResolver();
            ContentValues values =new ContentValues();
            values.put("data1",phone);

            if(!name.equals("")){
                mSelectClaus =ContactsContract.Contacts.DISPLAY_NAME+"=?";
                mSelectionArgs =new String[]{name};
                Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,SQL_COLUMN,mSelectClaus,mSelectionArgs,null);
                if(cursor.moveToFirst()){
                    rawContactId =cursor.getLong(0);
                }
                resolver.update(uri,values,"mimetype=? and raw_contact_id =?",new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,rawContactId+""
                });
                cursor.close();
                printQueryResult();
            }
        }

        //根据传入的姓名返回游标
        void getContact(String nameStr){
            mSelectClaus =ContactsContract.Contacts.DISPLAY_NAME+"=?";
            mSelectionArgs =new String[]{nameStr};
            Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,SQL_COLUMN,mSelectClaus,mSelectionArgs,null);
            if(cursor!=null){
                textView.setText("");
                while (cursor.moveToNext()){
                    String ID =cursor.getString(0);
                    String contactName =cursor.getString(1);
                    String photoNumber =cursor.getString(2);
                    textView.append("联系人ID："+ID+"\n联系人姓名："+contactName+"\n联系人电话："+photoNumber+"\n");
                }
                cursor.close();
            }
        }


        //删除
        void delete(){
            String name =userName.getText().toString();
            if(!name.equals("")){
                getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI,ContactsContract.Contacts.DISPLAY_NAME+"=?",new String[]{name});
            }
            printQueryResult();
        }

        //查询
        void query(){
            String name =userName.getText().toString();
            if(!name.equals("")){
                getContact(name);
            }
        }


        //根据游标返回全部数据
        void printQueryResult(){
            //content://com.android.contacts/data/phones
            //ContactsContract.CommonDataKinds常量类
            Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,SQL_COLUMN,null,null,null);
            if(cursor!=null){
                textView.setText("");
                while (cursor.moveToNext()){
                    String ID =cursor.getString(0);
                    String contactName =cursor.getString(1);
                    String photoNumber =cursor.getString(2);
                    textView.append("联系人ID："+ID+"\n联系人姓名："+contactName+"\n联系人电话："+photoNumber+"\n");
                }
                cursor.close();
            }
        }
    }



